package com.sen.demo.common.utils;

import io.jsonwebtoken.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

/**
 * @描述: jwt工具类
 * @作者: 韩宗森
 * @创建时间: 2025年08月18日 15:18
 */
public class JwtUtil {

    // 有效时长 默认24小时
    private static final Long JWT_TTL = 24 * 60 * 60 * 1000L;

    // 设置秘钥明文(盐)
    private static final String JWT_KEY = "123456";

    /**
     * 对 盐 进行加密
     * @return
     */
    public static SecretKey encodeKey() {
        byte[] bytes = Base64.getDecoder().decode(JWT_KEY);
        SecretKey key = new SecretKeySpec(bytes, 0, bytes.length, "AES");
        return key;
    }

    //根据用户id和用户名称生成token字符串
    public static String createToken(Long userId, String username) {
        long now = System.currentTimeMillis(); // 当前时间
        String token = Jwts.builder()
                //分类
                .setSubject("AUTH-USER")
                // 签发时间
                .setIssuedAt(new Date(now))
                //设置token有效时长
                .setExpiration(new Date(now + JWT_TTL))
                //设置主体部分
                .claim("userId", userId)
                .claim("username", username)
                //签名部分
                .signWith(SignatureAlgorithm.HS512, encodeKey())
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    // 解析token  从生成token字符串获取用户id
    public static Long getUserId(String token) {
        try {
            if (StringUtils.isEmpty(token)) {
                return null;
            }

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(encodeKey()).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    // 解析token 从生成token字符串获取用户名称
    public static String getUsername(String token) {
        try {
            if (StringUtils.isEmpty(token)) return "";

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(encodeKey()).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取请求中的access_token
     *
     * @param request HttpServletRequest
     * @return String
     */
    public static String getAccessToken(HttpServletRequest request) {
        // 从Authorization头部获取token
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7); // 去掉"Bearer "前缀
        }else {
            // 从参数中获取 token
            return request.getParameter("Authorization");
        }
    }

  /*  public static void main(String[] args) {
        String token = JwtUtil.createToken(3L, "xxaw");
        System.out.println("token: " + token);
        System.out.println("UserId: " + JwtUtil.getUserId(token));
        System.out.println("Username: " + JwtUtil.getUsername(token));
    }*/
}
